import QuickLRU from 'quick-lru';
import { isFunction } from 'lodash-es';

export class CacheManager {
    #store;

    constructor(maxSize = 100) {
        this.#store = new QuickLRU({
            maxSize,
            onEviction: (key, _value) => {
                console.debug(`Cache evicted: ${key}`, _value);
            }
        });
    }

    #generateKey(config, url, params) {
        if (config.key) {
            return isFunction(config.key) ? config.key() : config.key;
        }
        return `${url}:${JSON.stringify(params)}`;
    }

    set(url, data, config, params) {
        const key = this.#generateKey(config, url, params);
        const item = {
            data,
            expires: Date.now() + (config.timeout || 300) * 1000
        };
        this.#store.set(key, item);
    }

    get(url, config, params) {
        const key = this.#generateKey(config, url, params);
        const item = this.#store.get(key);

        if (!item) return null;

        if (Date.now() > item.expires) {
            this.#store.delete(key);
            return null;
        }

        return item.data;
    }

    delete(url, config, params) {
        const key = this.#generateKey(config, url, params);
        this.#store.delete(key);
    }

    clear() {
        this.#store.clear();
    }
}